package cn.guozeyiblog.client;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.select.Evaluator.ContainsOwnText;

import android.R.integer;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import cn.guozeyiblog.blogutils.ArticleDetail;
import cn.guozeyiblog.blogutils.Category;
import cn.guozeyiblog.blogutils.Link;
import cn.guozeyiblog.blogutils.Wechat;
import cn.guozeyiblog.client.ImageActivity.AsyGetImage;
import cn.guozeyiblog.client.XListView.IXListViewListener;
import cn.guozeyiblog.dbhelper.DBHelper;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.JsoupUtils;
import cn.guozeyiblog.netutils.NetWorkStatus;

public class MainAllAdapter extends BaseAdapter {

	private static String FLAG_ARTICLE_REFUSH="REFUSH";
	private static String FLAG_ARTICLE_LOAD="LOAD";
	private static String FLAG_WECHAT_LOAD="LOAD";
	private static String FLAG_ARTICLE_NODATA="NODATA";
	private static String FLAG_WECHAT_NODATA="NODATA";
	private static String FLAG_WECHAT_REFUSH="REFUSH";
	private List<View> viewList;
	private static Context context;
	private LayoutInflater inflater;
	private SharedPreferences preferences;
	private static ArrayList<ArticleDetail> listarticle = new ArrayList<>(); //文章
	private static ArticleAdapter articleAdapter;
	public static XListView articlelistView;
	private int articlepager=1;
	private static ArrayList<Category> listcategory = new ArrayList<>(); //分类
	private static CategoryAdapter categoryAdapter;
	public static ListView catelistView;
	private static ArrayList<Wechat> listwechat = new ArrayList<>(); //微语
	private static WechatAdapter wechatAdapter;
	public static XListView wechatlistView;
	private int wechatpager=1;
	private static String blogurl;
	private static ArrayList<Link> listlink = new ArrayList<>(); //链接
	public static ListView linkListView;
	private static LinkAdapter linkAdapter;
	private SQLiteDatabase db;
	ArrayList<ArticleDetail> lasttimeload = new ArrayList<>();
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			articleAdapter.notifyDataSetChanged();
			wechatAdapter.notifyDataSetChanged();
			categoryAdapter.notifyDataSetChanged();
			linkAdapter.notifyDataSetChanged();
		};
	};

	public MainAllAdapter(Context context) {
		//初始化数据
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		viewList = new ArrayList<View>();
		preferences = context.getSharedPreferences("cn.guozeyiblog.client_preferences", Context.MODE_PRIVATE);
		blogurl = preferences.getString("blogurl", "http://www.guozeyiblog.cn");
		db = new DBHelper(context, "Detail.db").getWritableDatabase();
		initViewList();
		initEveryList(); //初始化各个列表
	}

	public static ArrayList<ArticleDetail> getArticleList(){
		return listarticle;
	}
	public static ArrayList<Link> getLinkList(){
		return listlink;
	}
	public static ArrayList<Category> getCateList(){
		return listcategory;
	}
	public static ArrayList<Wechat> getWechatList(){
		return listwechat;
	}

	/**
	 * 初始化每个视图
	 */
	private void initViewList(){
		LinearLayout main_layout = initMainLayout();
		LinearLayout cate_layout = initCateLayout();
		LinearLayout wechat_layout = initWechatLayout();
		LinearLayout link_layout = initLinkLayout();
		viewList.add(main_layout);
		viewList.add(cate_layout);
		viewList.add(wechat_layout);
		viewList.add(link_layout);
	}
	private LinearLayout initLinkLayout() {
		// TODO Auto-generated method stub
		LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.link_list, null);
		linkListView = (ListView) layout.findViewById(R.id.links_list);
		linkAdapter = new LinkAdapter(listlink, context);
		linkListView.setAdapter(linkAdapter);
		linkListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, WebViewActivity.class);
				intent.putExtra("url", listlink.get(position).getLink());
				intent.putExtra("title", listlink.get(position).getName());
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});
		return layout;
	}
	public static void notifylinkdatachange(){
		linkListView.invalidate();
		linkAdapter.notifyDataSetChanged();
	}

	private LinearLayout initWechatLayout() {
		// TODO Auto-generated method stub
		LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.wechat_list, null);
		wechatlistView = (XListView) layout.findViewById(R.id.wechats_list);
		wechatAdapter = new WechatAdapter(listwechat, context);
		wechatlistView.setAdapter(wechatAdapter);
		wechatlistView.setPullLoadEnable(true);
		//wechatlistView.setEnabled(false);
		wechatlistView.setXListViewListener(new MyIxListViewListener4Wechat());
		return layout;
	}
	public static void notifywechatdatachange(){
		wechatlistView.invalidate();
		wechatAdapter.notifyDataSetChanged();
	}

	private LinearLayout initCateLayout() {
		// TODO Auto-generated method stub
		LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.category_list, null);
		catelistView = (ListView) layout.findViewById(R.id.cate_list);
		categoryAdapter = new CategoryAdapter(listcategory, context);
		catelistView.setAdapter(categoryAdapter);
		catelistView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, CateArticleListActivity.class);
				intent.putExtra("url", listcategory.get(position).getUrl());
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});
		return layout;
	}
	public static void notiycatedatachange(){
		catelistView.invalidate();
		categoryAdapter.notifyDataSetChanged();
	}

	private LinearLayout initMainLayout() {
		// TODO Auto-generated method stub
		LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.main_article_list, null);
		articlelistView = (XListView) layout.findViewById(R.id.article_list);
		articleAdapter = new ArticleAdapter(listarticle, context);
		articlelistView.setAdapter(articleAdapter);
		articlelistView.setPullLoadEnable(true);
		articlelistView.setRefreshTime(preferences.getString("last_update", "没有刷新记录"));
		articlelistView.setXListViewListener(new MyIxListViewListener4Article());
		articlelistView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(context, ArticleDetailActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//-----------------------------------------------------------sdk 11
				intent.putExtra("url", listarticle.get(position-1).getLink());
				context.startActivity(intent);
			}
		});
		return layout;
	}

	public static void notifyarticledatachange(){
		articlelistView.invalidate();
		articleAdapter.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return viewList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return viewList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		//Toast.makeText(context, position+"getView", 0).show();
		return viewList.get(position);
	}

	public  void initEveryList(){
		//在此获取主页面的数据
		//new AsyGetBlogList().execute(blogurl,FLAG_ARTICLE_REFUSH);
		new Thread(){@Override
			public void run() {
			// TODO Auto-generated method stub
			listarticle.addAll(getArticleFromDB());
			listwechat.addAll(getWechatFromDB());
			listcategory.addAll(getCategorieFromDB());
			listlink.addAll(getLinkFromDB());
			handler.sendEmptyMessage(0);
			super.run();
		}}.start();
		if(NetWorkStatus.isNetworkAvailable(context)){
			new AsyGetWechatList().execute(blogurl+"/t/",FLAG_WECHAT_REFUSH);
			new AsyGetCateList().execute(blogurl);
			new AsyGetLinkList().execute(blogurl);
		}else {
			Toast.makeText(context, "你的网络不可用哦", 0).show();
		}
		
	}


	/**
	 * 从数据库中取出本地数据
	 * @return
	 */
	public ArrayList<ArticleDetail> getArticleFromDB(){
		ArrayList<ArticleDetail> locallist;
		locallist = new ArrayList<>();
		Cursor cursor = db.query(ArticleDetail.TABLE, null, null, null, null, null, ArticleDetail.ID+" DESC");
		while (cursor.moveToNext()) {
			ArticleDetail article = new ArticleDetail();
			article.setTitle(cursor.getString(cursor.getColumnIndex(ArticleDetail.TITLE)));
			article.setCommentCount(cursor.getString(cursor.getColumnIndex(ArticleDetail.COMMENTCOUNT)));
			article.setDate(cursor.getString(cursor.getColumnIndex(ArticleDetail.DATE)));
			article.setId(cursor.getInt(cursor.getColumnIndex(ArticleDetail.ID)));
			article.setLink(cursor.getString(cursor.getColumnIndex(ArticleDetail.LINK)));
			article.setViewCount(cursor.getString(cursor.getColumnIndex(ArticleDetail.VIEWCOUNT)));
			article.setDescription(cursor.getString(cursor.getColumnIndex(ArticleDetail.DESCRIPTION)));
			locallist.add(article);
		}
		return locallist;
	}


	/**
	 * 从数据库中取出Wechat
	 * @return
	 */
	public ArrayList<Wechat> getWechatFromDB(){
		ArrayList<Wechat> locallist = new ArrayList<>();
		Cursor cursor = db.query(Wechat.TABLE, null, null, null, null, null, null);
		while(cursor.moveToNext()){
			Wechat wechat = new Wechat();
			wechat.setContent(cursor.getString(cursor.getColumnIndex(Wechat.CONTENT)));
			wechat.setUser(cursor.getString(cursor.getColumnIndex(Wechat.USER)));
			locallist.add(wechat);
		}
		return locallist;
	}


	/**
	 * 从数据库取出分类
	 */
	public ArrayList<Category> getCategorieFromDB(){
		ArrayList<Category> locallist = new ArrayList<>();
		Cursor cursor = db.query(Category.TABLE, null, null, null, null, null, null);
		while (cursor.moveToNext()) {
			Category category = new Category(cursor.getString(cursor.getColumnIndex(Category.NAME)), 
					cursor.getString(cursor.getColumnIndex(Category.URL)));
			locallist.add(category);
		}
		return locallist;
	}

	public ArrayList<Link> getLinkFromDB(){
		ArrayList<Link> locaLinks = new ArrayList<>();
		Cursor cursor = db.query(Link.TABLE, null, null, null, null, null, null);
		while(cursor.moveToNext()){
			Link link = new Link(cursor.getString(cursor.getColumnIndex(Link.NAME)),
					cursor.getString(cursor.getColumnIndex(Link.LINK)));
			locaLinks.add(link);
		}
		return locaLinks;
	}

	/**
	 * ArticleList异步请求
	 * @author kutear
	 *
	 */
	class AsyGetBlogList extends AsyncTask<String, String, Void>{


		public boolean IsSameWithLastTime(ArrayList<ArticleDetail> addlist){
			for (int i = 0; i < lasttimeload.size(); i++) {
				if (lasttimeload.get(i).getId()==addlist.get(0).getId()) {
					return true;
				}
			}
			return false;
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			if (result!=null) {
				ArrayList<ArticleDetail> addlist = JsoupUtils.GetBlogList(result);
				if (addlist.size()>0) {
					//刷新
					if (params[1].equals(FLAG_ARTICLE_REFUSH)) { //判断是通过刷新还是加载得到的数据
						boolean flag = false;   //判断是否加载新数据的标志
						for (int i = addlist.size()-1; i>=0;i--) {
							//判断是否已经存在
							if (!Contains(addlist.get(i))) {
								listarticle.add(0,addlist.get(i));
								flag = true;
								//加入数据库
							
								insertArticleToDB(addlist.get(i));
							}
						}
						if (!flag) {  //加载到的数据都是重复的
							publishProgress(FLAG_ARTICLE_NODATA);
						}
						//加载	
					}else {
						if (IsSameWithLastTime(addlist)) {
							publishProgress(FLAG_ARTICLE_NODATA);
						}else{
							lasttimeload = addlist;
							boolean flag = false;   //判断是否加载新数据的标志
							for (int i = addlist.size()-1; i>=0;i--) {
								if (!Contains(addlist.get(i))) {
									listarticle.add(addlist.get(i));
									flag = true;
									//数据库只存储最新的10条数据
									if(listarticle.get(0).getId()-10 < addlist.get(i).getId()){
										insertArticleToDB(addlist.get(i));
									}
									
								}
							}
							if (!flag) {
								//publishProgress(FLAG_ARTICLE_NODATA);
								//next pager;
								articlepager++;
								new AsyGetBlogList().execute(blogurl+"/?page="+articlepager,FLAG_ARTICLE_LOAD);
							}
						}
					}
				}else {
					publishProgress(FLAG_ARTICLE_NODATA);
				}



//				for (ArticleDetail d:listarticle) {
//					System.out.println("articletitle"+d.getTitle());
//				}
				publishProgress("");
			}
			return null;
		}

		public boolean DBContain(ArticleDetail a){
			for(ArticleDetail b:getArticleFromDB()){
				if (b.getId()==a.getId()) {
					return true;
				}
			}
			return false;
		}
		public void insertArticleToDB(ArticleDetail a){
			if (DBContain(a)) {
				return;
			}
			ContentValues values = new ContentValues();
			values.put(ArticleDetail.ID, a.getId());
			values.put(ArticleDetail.TITLE, a.getTitle());
			values.put(ArticleDetail.DATE, a.getDate());
			values.put(ArticleDetail.DESCRIPTION, a.getDescription());
			values.put(ArticleDetail.COMMENTCOUNT, a.getCommentCount());
			values.put(ArticleDetail.VIEWCOUNT, a.getViewCount());
			values.put(ArticleDetail.LINK, a.getLink());
			db.insert(ArticleDetail.TABLE, null, values);
		}

		//判断listarray中是否包含某个对象
		public boolean Contains(ArticleDetail a){
			for (int i = 0; i < listarticle.size(); i++) {
				if (listarticle.get(i).getId()==a.getId()) {
					return true;
				}
			}
			return false;
		}


		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			Log.v(">>>>>>>", "onprogressUpdate");
			if (values[0].equals(FLAG_ARTICLE_NODATA)) {
				Toast.makeText(context, "no more data", 0).show();
				return ;
			}
			articleAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//停止刷新...setting time
			articlelistView.stopLoadMore();
			articlelistView.stopRefresh();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			articlelistView.setRefreshTime(time);
			Editor editor = preferences.edit();
			editor.putString("last_update", time);
			editor.commit();
			articleAdapter.notifyDataSetChanged();
		}
	}


	/**
	 * Wechat 异步请求
	 * @author kutear
	 *
	 */
	class AsyGetWechatList extends AsyncTask<String, String, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			ArrayList<Wechat> addlist = JsoupUtils.getWechats(result);
			if (addlist.size()>0) {  //如果获取到数据
				//刷新数据
				if (params[1].equals(FLAG_WECHAT_REFUSH)) {
					boolean flag = false;
					for (int i = addlist.size()-1; i>=0;i--) {
						if (!Contains(addlist.get(i))) {
							listwechat.add(0,addlist.get(i));
							flag = true;
							insertWechatToDb(addlist.get(i));
						}
					}
					if (!flag) {
						//没有数据
						publishProgress(FLAG_WECHAT_NODATA);
					}
					//加载数据	
				}else {
					boolean flag = false;
					for (int i = addlist.size()-1; i>=0;i--) {
						if (!Contains(addlist.get(i))) {
							listwechat.add(addlist.get(i));
							flag = true;
							insertWechatToDb(addlist.get(i));
						}
					}
					if (!flag) {
						publishProgress(FLAG_WECHAT_NODATA);
					}
				}
			}else {
				publishProgress(FLAG_WECHAT_NODATA);
				return null;
			}
			publishProgress("");
			return null;
		}

		public boolean DBContains(Wechat w){
			for (Wechat a:getWechatFromDB()) {
				if (a.getContent().equals(w.getContent())&&a.getUser().equals(w.getUser())) {
					return true;
				}			
			}
			return false;
		}
		public void insertWechatToDb(Wechat w){
			//检测是否存在
			if (DBContains(w)) {
				return ;
			}			
			ContentValues values = new ContentValues();
			values.put(Wechat.CONTENT, w.getContent());
			values.put(Wechat.USER, w.getUser());
			db.insert(Wechat.TABLE, null, values);
		}

		public boolean Contains(Wechat w){
			for (int i = 0; i < listwechat.size(); i++) {
				if ((listwechat.get(i).getContent().equals(w.getContent())
						&&listwechat.get(i).getUser().equals(w.getUser()))) {
					return true;
				}
			}
			return false;

		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			if (values[0].equals(FLAG_WECHAT_NODATA)) {
				//Toast.makeText(context, "no more data", 0).show();
				return ;
			}
			//wechatAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//停止刷新...setting time
			Log.v("MainAllAdapter", "OnPostExecute");
			wechatlistView.stopLoadMore();
			wechatlistView.stopRefresh();
			wechatlistView.setRefreshTime("just now");
			wechatAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 友链的获取
	 * @author kutear
	 *
	 */
	public class AsyGetLinkList extends AsyncTask<String, String, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(blogurl);
			ArrayList<Link> addList = JsoupUtils.GetLinkList(result);
			if (addList.size()==0) {
				publishProgress("can't get more data");
			}else {
				for (int i = 0; i < addList.size(); i++) {
					if (!Contains(addList.get(i))) {
						listlink.add(addList.get(i));
						insertLinkToDB(addList.get(i));
					}
				}
			}
			return null;
		}

		public boolean DBContain(Link l){
			for(Link a:getLinkFromDB()){
				if (a.getLink().equals(l.getLink())&&a.getName().equals(l.getName())) {
					return true;
				}
			}
			return false;
		}
		public boolean Contains(Link l){
			for (int i = 0; i < listlink.size(); i++) {
				if (l.getLink().equals(listlink.get(i).getLink())&&
						l.getName().equals(listlink.get(i).getName())) {
					return true;
				}
			}
			return false;
		}

		public void insertLinkToDB(Link l){
			if(DBContain(l)){
				return ;
			}
			ContentValues values = new ContentValues();
			values.put(Link.NAME, l.getName());
			values.put(Link.LINK, l.getLink());
			db.insert(Link.TABLE, null, values);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			linkAdapter.notifyDataSetChanged();
		}

	}
	/**
	 * 异步请求分类列表
	 * @author kutear
	 *
	 */
	public class AsyGetCateList extends AsyncTask<String, String, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			if (JsoupUtils.GetCateList(result).size()==0) {
				publishProgress("can't get more data");
			}else {
				ArrayList<Category> addlist = JsoupUtils.GetCateList(result);
				for (int i=0;i<addlist.size();i++) {
					if (!Contains(addlist.get(i))) {
						insertCateToDB(addlist.get(i));
						listcategory.add(addlist.get(i));
					}
				}
			}
			return null;
		}

		public boolean DBContains(Category w){
			for (Category c:getCategorieFromDB()) {
				if (c.getCategroyName().equals(w.getCategroyName())&&c.getUrl().equals(w.getUrl())) {
					return true;
				}			
			}
			return false;
		}

		public boolean Contains(Category c){
			for (int i = 0; i < listcategory.size(); i++) {
				if (c.getCategroyName().equals(listcategory.get(i).getCategroyName())&&
						c.getUrl().equals(listcategory.get(i).getUrl())) {
					return true;
				}
			}
			return false;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

		public void insertCateToDB(Category c){
			if (DBContains(c)) {
				return ;
			}
			ContentValues values = new ContentValues();
			values.put(Category.NAME, c.getCategroyName());
			values.put(Category.URL, c.getUrl());
			db.insert(Category.TABLE, null, values);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			Toast.makeText(context, values[0], 0).show();
			super.onProgressUpdate(values);
			categoryAdapter.notifyDataSetChanged();
		}
	}


	/**
	 * 实现IxListviewListenr接口 for Article
	 * @author kutear
	 *
	 */
	public class MyIxListViewListener4Article implements IXListViewListener{
		@Override
		public void onRefresh() {
			// TODO Auto-generated method stub
			new AsyGetBlogList().execute(blogurl,FLAG_ARTICLE_REFUSH);
		}

		@Override
		public void onLoadMore() {
			// TODO Auto-generated method stub
			articlepager++;
			new AsyGetBlogList().execute(blogurl+"/?page="+articlepager,FLAG_ARTICLE_LOAD);
			Log.v("MainAllAdapter","Article_loadmore");
		}
	}

	/**
	 * 实现IxListviewListenr接口 for Wechat
	 * @author kutear
	 *
	 */
	public class MyIxListViewListener4Wechat implements IXListViewListener{
		@Override
		public void onRefresh() {
			// TODO Auto-generated method stub
			new AsyGetWechatList().execute(blogurl+"/t/",FLAG_WECHAT_REFUSH);
		}

		@Override
		public void onLoadMore() {
			// TODO Auto-generated method stub
			wechatpager++;
			new AsyGetWechatList().execute(blogurl+"/t/?page="+wechatpager,FLAG_WECHAT_LOAD);
			Log.v("MainAllAdapter","Wechat_loadmore");
		}
	}
}
